import { MovieModel } from "../db";
import { IMovie } from "../db/MovieSchema";
import { ISearchResult } from "../entities/CommonTyoes";
import { Movie } from "../entities/Movie";
import { SearchCondition } from "../entities/SearchConditions";

export class MovieServices {
    /**
     * # 添加电影
     * @param movie 电影实体类
     * @returns 成功返回添加的电影，失败返回错误信息
     */
    public static async addMovies(movie: Movie): Promise<IMovie | string[]> {
        // 1. 转换类型
        movie = Movie.transform(movie)
        // 2. 数据验证
        const errors = await movie.validateThis()
        if (errors.length) {
            return errors;
        }
        // 3. 添加到数据库
        const result = await MovieModel.create(movie)
        return result
    }

    /**
     * # 编辑电影信息 
     * @param movieId 电影ID
     * @param movie 
     */
    public static async editMovies(movieId: string, movie: Movie): Promise<string[]> {
        // 1. 转换类型
        const tempMovie = Movie.transform(movie)
        // 2. 数据验证
        const errors = await tempMovie.validateThis(true)
        if (errors.length) {
            return errors
        }
        // 3. 编辑电影信息
        await MovieModel.updateOne({ _id: movieId }, movie)
        return errors;
    }

    /**
     * # 删除电影信息
     * @param movieId 电影ID
     */
    public static async deleteMovie(movieId: string): Promise<void> {
        await MovieModel.deleteOne({ _id: movieId })
    }

    public static async findById(movieId: string): Promise<IMovie | null> {
        const result = await MovieModel.findById(movieId)
        return result
    }

    public static async find(condition: SearchCondition): Promise<ISearchResult<IMovie>> {
        // 1. 转换类型
        const searchCondition = SearchCondition.transform(condition)
        // 2. 数据验证
        const errors = await searchCondition.validateThis()
        if (errors.length) {
            return {
                total: 0,
                data: [],
                errors
            };
        }
        // 3，查询电影信息
        const movieList = await MovieModel.find({
            name: { $regex: new RegExp(searchCondition.key) }
        }).skip((searchCondition.page) * searchCondition.limit).limit(searchCondition.limit);

        const movieCount = await MovieModel.find({
            name: { $regex: new RegExp(searchCondition.key) }
        }).countDocuments()

        return {
            total: movieCount,
            data: movieList,
            errors: []
        }
    }
}  